// +----------------------------------------------------------------------
// | 描述: Dom处理工具
// +----------------------------------------------------------------------
// | 作者: cleverstone
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

/**
 * Code Assist
 * @type {{evalScript(*): never, scrollTop(*, *=, *=, *=, *=): void}}
 */
module.exports = {
    /**
     * 滚动到顶部(动画效果)
     * @param el
     * @param from
     * @param to
     * @param duration
     * @param endCallback
     */
    scrollTop(el, from = 0, to, duration = 500, endCallback) {
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = (
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function (callback) {
                    return window.setTimeout(callback, 1000 / 60)
                }
            )
        }
        const difference = Math.abs(from - to)
        const step = Math.ceil(difference / duration * 50)

        function scroll(start, end, step) {
            if (start === end) {
                endCallback && endCallback()
                return
            }

            let d = (start + step > end) ? end : start + step
            if (start > end) {
                d = (start - step < end) ? end : start - step
            }

            if (el === window) {
                window.scrollTo(d, d)
            } else {
                el.scrollTop = d
            }

            window.requestAnimationFrame(() => scroll(d, end, step))
        }

        scroll(from, to, step)
    },

    /**
     * 解析js脚本
     * @param script
     * @return {never}
     */
    evalScript(script) {
        let fn = new Function(`return ${script}`)

        return fn()
    }
}
